<script setup lang="ts">
import {ref} from 'vue'
import {User, Lock} from '@element-plus/icons-vue'
import {ElMessage, type FormInstance} from 'element-plus'
import axios from 'axios';
import { useRouter } from 'vue-router'
import sha256 from 'crypto-js/sha256.js'
const userAccount = ref('')
const userPassword = ref('')
const checkPassword = ref('')



interface RegisterData {
  userAccount: string
  userPassword: string
  checkPassword: string
}

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)


const validatePasswordConfirm = (_: unknown, value: string, callback: (error?: Error) => void) => {
  if (value !== userPassword.value) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 6, max: 14, message: '账号长度需在6-14位之间', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '账号只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 14, message: '密码长度需在8-14位之间', trigger: 'blur' }
  ],
  checkPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePasswordConfirm, trigger: 'blur' }
  ]
}

const submit = async () => {

  try {
    loading.value = true

    // 表单验证
    await formRef.value?.validate()
    const encryptedPassword = sha256(userPassword.value).toString()
    const encryptedCheckPassword = sha256(checkPassword.value).toString()
    const requestData: RegisterData = {
      userAccount: userAccount.value.trim(),
      userPassword: encryptedPassword,
      checkPassword: encryptedCheckPassword
    }
    console.log(requestData)
    const response = await axios.post(
        '/api/user/register',
        requestData,
        {
          headers: {
            'Content-Type': 'application/json'
          }
        }
    )

    if (response.data.code === 200) {
      ElMessage.success('注册成功')
      setTimeout(() => {
        loading.value = false
        window.location.reload()
      }, 1000)
    } else {
      ElMessage.error( '注册失败')
      console.log(requestData)
      console.log(response)
    }
  } catch (error) {
    if (axios.isAxiosError(error)) {
      const errorMessage = error.response?.data?.message || '网络请求失败'
      ElMessage.error(errorMessage)
    } else if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}
</script>
<template>
  <div class="register">
    <el-form
        ref="formRef"
        :model="{ userAccount, userPassword, checkPassword }"
        :rules="rules"
        label-position="top"
        status-icon>  <!-- 添加验证状态图标 -->
      <el-form-item prop="userAccount">  <!-- 包裹输入框 -->
        <el-input
            id="register-userAccount-input"
            maxlength="14"
            v-model="userAccount"
            style="width: 320px"
            placeholder="请输入您的账号"
            :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item prop="userPassword">  <!-- 包裹输入框 -->
        <el-input
            id="register-userPassword-input"
            maxlength="14"
            v-model="userPassword"
            style="width: 320px"
            type="password"
            placeholder="请输入您的密码"
            :prefix-icon="Lock"
            show-password
        />
      </el-form-item>

      <el-form-item prop="checkPassword">  <!-- 包裹输入框 -->
        <el-input
            id="register-checkPassword-input"
            maxlength="14"
            v-model="checkPassword"
            style="width: 320px"
            type="password"
            placeholder="请确认您的密码"
            :prefix-icon="Lock"
            show-password
        />
      </el-form-item>

      <el-button
          type="primary"
          id="register-btn"
          @click="submit"
          :loading="loading">  <!-- 添加加载状态 -->
        注册
      </el-button>
    </el-form>
  </div>
</template>

<style scoped>
.register {
  .el-input {
    /*输入框圆角曲率*/
    --el-input-border-radius: 8px;
    height: 40px;
  }

  :deep(.el-input__inner) {
    font-size: 16px !important;
  }

  #register-btn {
    width: 320px;
    height: 40px;
    font-size: 16px;
    color: #fff;
    margin-top: 2px;
    border-radius: 8px;
  }
}
</style>